package com.wanmait.community.validation.usableArea;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;

public class UsableAreaValidator implements ConstraintValidator<ValidUsableArea, Object> {

    @Override
    public void initialize(ValidUsableArea constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {
        if (object == null) {
            return true; // 或根据业务逻辑返回 false
        }

        try {
            Field grossAreaField = object.getClass().getDeclaredField("grossArea");
            Field usableAreaField = object.getClass().getDeclaredField("usableArea");
            grossAreaField.setAccessible(true);
            usableAreaField.setAccessible(true);

            Object grossAreaValue = grossAreaField.get(object);
            Object usableAreaValue = usableAreaField.get(object);

            // 检查字段是否存在且类型正确
            if (!(grossAreaValue instanceof Double) || !(usableAreaValue instanceof Double)) {
                throw new IllegalArgumentException("字段类型必须为 Double");
            }

            Double grossArea = (Double) grossAreaValue;
            Double usableArea = (Double) usableAreaValue;

            // 允许字段为空（由 @NotNull 校验）
            if (grossArea == null || usableArea == null) {
                return true;
            }

            // 核心逻辑：室内面积 ≤ 建筑面积
            return usableArea <= grossArea;

        } catch (NoSuchFieldException e) {
            throw new RuntimeException("字段不存在: " + e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("非法访问字段", e);
        } catch (ClassCastException | IllegalArgumentException e) {
            throw new RuntimeException("字段类型不匹配或值非法", e);
        } catch (Exception e) {
            throw new RuntimeException("未知异常: " + e.getMessage(), e);
        }
    }
}
